package com.fingard.dsp.bank.directbank.boc03;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 境外它行 明细查询
 * @param
 * @return
 * @throws Exception
 */
public class BOC03Transaction extends BOC03Base implements ITransaction {

    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        retAtsTrans.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo ="";
        try{
            //起始日期
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            //结束日期
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while(tmpIntDateFrom<=tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)){
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //当是跨月查询时，先查询起始日期到月末日期记录，再查询月末后一天日期到结束日期记录
                if(DateHelper.compareMonth(tmpCalendarFrom,tmpCalendarTo)==-1){
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH,tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                }else{
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                int tmpNowReadStart = 1;//起始笔数
                int tmpNowReadNum = 0;//已查询笔数
                Map<String,Integer> tmpTotalNum = new HashMap<String, Integer>();
                while (tmpNowReadNum==0 || tmpNowReadNum<tmpTotalNum.get("totalCount")) {
                    //======拼接报文======
                    BOC03Header bankHeader = new BOC03Header();
                    bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
                    bankHeader.trncod = "b2e0235";//交易代码
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    writeCommonHeader2(xmlWriter, bankHeader);
                    xmlWriter.writeStartElement("trn-b2e0235-rq");
                    xmlWriter.writeStartElement("b2e0235-rq");
                    xmlWriter.writeElementString("actacn", p_req7516.actNum);
                    xmlWriter.writeElementString("swiftcode", p_req7516.swiftCode);//账户所在行的swiftcode
                    xmlWriter.writeElementString("begnum", tmpNowReadStart+"");//起始记录号
                    xmlWriter.writeElementString("recnum", "50");//默认查询笔数
                    xmlWriter.writeStartElement("datescope");
                    xmlWriter.writeElementString("from", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("to", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndDocument();
                    //======拼接报文======
                    //发送请求报文
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

                    //测试
                    //String[] tmpStrRet=new String[]{"",FileHelper.readFileText("D:\\zjbr-接口测试\\25.中行联行号下载\\境外账户查询\\rsp\\b2e0235.xml","utf-8")};

                    //处理响应
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmprspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0235-rs/status/rspcod");
                            String tmprspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0235-rs/status/rspmsg");
                            if (isActiveRetCode(tmprspcod)) {
                                String totalCount = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0235-rs/totalnum");//总笔数
                                //String backnum = tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0235-rs/backnum");//返回记录数
                                if(tmpTotalNum.containsKey("totalCount")){
                                    if(tmpTotalNum.get("totalCount").intValue()!=Integer.valueOf(totalCount).intValue()){
                                        tmpRespCode ="-1";
                                        tmpRespInfo = "相同条件前后查出来的总数不一致";
                                        break;
                                    }
                                }else{
                                    if("0".equals(totalCount)){
                                        tmpRespCode ="0";
                                        tmpRespInfo = "该时间段的总明细条数为0";
                                        break;
                                    }
                                    tmpTotalNum.put("totalCount",Integer.valueOf(totalCount));//记录总条数
                                }
                                //B028 账户无交易 B003 交易数为0
                                int readCount=0;
                                if (!"B028".equals(tmprspcod) && !"B003".equals(tmprspcod)) {
                                    if ("B001".equals(tmpBkReader.getFirstText("/bocb2e/trans/trn-b2e0235-rs/b2e0235-rs/status/rspcod"))) {
                                        while (tmpBkReader.read("/bocb2e/trans/trn-b2e0235-rs/b2e0235-rs/detail")) {
                                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                            tmpRetDetail.actArea = p_req7516.actArea;//海外机构号
                                            tmpRetDetail.actNum = p_req7516.actNum;//账号
                                            tmpRetDetail.tranDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleText("chargedate"));//交易日期
                                            tmpRetDetail.tranTime = tmpRetDetail.tranDate + " 00:00:00";//交易时间
                                            tmpRetDetail.valueDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleText("frvaldat"));//起息日期
                                            String tranAmt = tmpBkReader.readedXElement.getSingleText("txamt");//交易金额
                                            String cdFlag = tmpBkReader.readedXElement.getSingleText("flag");//C D RC RD
                                            if ("D".equals(cdFlag) || "RC".equals(cdFlag)) {
                                                if (tranAmt.contains("-")) {
                                                    tmpRetDetail.tranAmt = tranAmt.substring(1);
                                                    tmpRetDetail.cdFlag = "2";
                                                } else {
                                                    tmpRetDetail.tranAmt = tranAmt;
                                                    tmpRetDetail.cdFlag = "1";
                                                }
                                            } else if ("C".equals(cdFlag) || "RD".equals(cdFlag)) {
                                                if (tranAmt.contains("-")) {
                                                    tmpRetDetail.tranAmt = tranAmt.substring(1);
                                                    tmpRetDetail.cdFlag = "1";
                                                } else {
                                                    tmpRetDetail.tranAmt = tranAmt;
                                                    tmpRetDetail.cdFlag = "2";
                                                }
                                            }
                                            if(tmpRetDetail.tranAmt.contains("+")){
                                                tmpRetDetail.tranAmt=tmpRetDetail.tranAmt.substring(1);
                                            }
                                            tmpRetDetail.billType = tmpBkReader.readedXElement.getSingleText("busitype");//业务类型
                                            tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("extinfo");//摘要
                                            tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);//对账码
                                            tmpRetDetail.askNumber = tmpBkReader.readedXElement.getSingleText("bankrefseq");//交易编号
                                            tmpRetDetail.cur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("pydcur"));//交易币种
                                            tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleText("bankrefseq");//交易编号
                                            retAtsTrans.writeRetDetail(tmpRetDetail);
                                            readCount++;
                                        }
                                    }
                                }
                                tmpNowReadNum +=readCount;//已查询条数
                                tmpNowReadStart +=readCount;//下一次起始位置=起始位置+循环次数
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmprspmsg;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        }catch (Exception ex){
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:"+ex);
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        }else if(retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespInfo("交易为空");
            retAtsTrans.writeRespCode("0");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        return null;
    }
}
